package ynu.edu.controller;

import jakarta.annotation.Resource;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import ynu.edu.entity.User;

import java.util.Map;

@RestController
@RequestMapping("/rest")
@RefreshScope  // 配置更新域
public class RestTemplateDemoController {
    
    @Resource
    private RestTemplate restTemplate;
    
    // 使用服务名，LoadBalancer会自动进行负载均衡
    private static final String SERVICE_URL = "http://provider-service";
    
    /**
     * 使用RestTemplate进行GET调用 - 根据ID获取用户
     */
    @GetMapping("/getUserById/{userId}")
    public User getUserById(@PathVariable("userId") Integer userId) {
        String url = SERVICE_URL + "/user/getUserById/" + userId;
        return restTemplate.getForObject(url, User.class);
    }
    
    /**
     * 使用RestTemplate进行GET调用 - 获取所有用户
     */
    @GetMapping("/getAllUsers")
    public Map<String, Object> getAllUsers() {
        String url = SERVICE_URL + "/user/getAllUsers";
        ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
        return response.getBody();
    }
    
    /**
     * 使用RestTemplate进行POST调用 - 创建用户
     */
    @PostMapping("/createUser")
    public Map<String, Object> createUser(@RequestBody User user) {
        String url = SERVICE_URL + "/user/createUser";
        
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<User> entity = new HttpEntity<>(user, headers);
        
        // 发送POST请求
        ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
        return response.getBody();
    }
    
    /**
     * 使用RestTemplate进行PUT调用 - 更新用户
     */
    @PutMapping("/updateUser/{userId}")
    public Map<String, Object> updateUser(@PathVariable("userId") Integer userId, @RequestBody User user) {
        String url = SERVICE_URL + "/user/updateUser/" + userId;
        
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<User> entity = new HttpEntity<>(user, headers);
        
        // 发送PUT请求
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.PUT, entity, Map.class);
        return response.getBody();
    }
    
    /**
     * 使用RestTemplate进行DELETE调用 - 删除用户
     */
    @DeleteMapping("/deleteUser/{userId}")
    public Map<String, Object> deleteUser(@PathVariable("userId") Integer userId) {
        String url = SERVICE_URL + "/user/deleteUser/" + userId;
        
        // 发送DELETE请求
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.DELETE, null, Map.class);
        return response.getBody();
    }
    
    /**
     * 负载均衡测试接口 - 多次调用查看负载均衡效果
     */
    @GetMapping("/loadBalanceTest")
    public Map<String, Object> loadBalanceTest() {
        String url = SERVICE_URL + "/user/getAllUsers";
        
        // 连续调用10次，观察随机负载均衡效果
        java.util.List<String> results = new java.util.ArrayList<>();
        int count11000 = 0;
        int count11001 = 0;
        
        for (int i = 0; i < 10; i++) {
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            Map<String, Object> body = response.getBody();
            if (body != null && body.get("message") != null) {
                String message = body.get("message").toString();
                results.add("第" + (i + 1) + "次调用: " + message);
                
                // 统计调用分布
                if (message.contains("from 11000")) {
                    count11000++;
                } else if (message.contains("from 11001")) {
                    count11001++;
                }
            }
        }
        
        return Map.of(
                "testType", "RestTemplate随机负载均衡测试",
                "strategy", "Random LoadBalancer",
                "results", results,
                "statistics", Map.of(
                        "total", 10,
                        "server11000", count11000,
                        "server11001", count11001,
                        "distribution", count11000 + ":" + count11001
                ),
                "explanation", "随机策略：观察调用分布应该是随机的，不是1:1轮询"
        );
    }
} 